package pd_client

import (
	"log"
	"net"
	"strings"

	"golang.org/x/net/proxy"
)

func NewSocks5ProxyClient(deviceID string, network, address string) (proxy.Dialer, error) {
	p, err := proxy.SOCKS5(network, address, nil, NewSocks5Client(deviceID))
	if err != nil {
		log.Println(err)
	}

	return p, err
}

type Socks5Client struct {
	deviceID []byte
}

func NewSocks5Client(deviceID string) *Socks5Client {
	var newDeviceID string
	if len(deviceID) >= 20 {
		newDeviceID = deviceID[:20]
	} else {
		newDeviceID = deviceID + strings.Repeat(" ", 20-len(deviceID))
	}
	return &Socks5Client{
		deviceID: []byte(newDeviceID),
	}
}

func (tis *Socks5Client) Dial(network, addr string) (net.Conn, error) {
	log.Println(network, addr)
	conn, err := net.Dial(network, addr)
	if err != nil {
		log.Println(err)
		return nil, err
	}

	if _, err = conn.Write(tis.deviceID); err != nil {
		return nil, err
	}

	return conn, nil
}
